package vaccine.appointment.system.user.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import vaccine.appointment.system.common.annotation.AutoWrapResult;
import vaccine.appointment.system.common.annotation.RequireRole;
import vaccine.appointment.system.user.enums.IdentityInfoEnum;
import vaccine.appointment.system.user.service.UserService;
import vaccine.appointment.system.user.vo.ChangePasswordRequest;
import vaccine.appointment.system.user.vo.LoginRequest;
import vaccine.appointment.system.user.vo.LoginResponse;
import vaccine.appointment.system.user.vo.RegisterRequest;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * 用户控制器
 */
@AutoWrapResult
@RequestMapping("/user")
@RestController
@Validated
@CrossOrigin(origins = {"http://localhost:5173", "http://127.0.0.1:5173"}, allowCredentials = "true")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 用户登录
     * @param loginRequest 登录请求信息
     * @return 登录响应（包含JWT token）
     */
    @PostMapping("/login")
    public LoginResponse login(@Valid @RequestBody LoginRequest loginRequest) {
        return userService.login(loginRequest.getAccount(), loginRequest.getPassword());
    }

    /**
     * 用户注册
     * @param registerRequest 注册请求信息
     * @return 注册是否成功
     */
    @PostMapping("/register")
    public Boolean register(@Valid @RequestBody RegisterRequest registerRequest) {
        return userService.register(registerRequest);
    }

    /**
     * 修改密码
     * @param request 修改密码请求
     * @param httpRequest HTTP请求
     * @return 是否成功
     */
    @PutMapping("/password")
    @RequireRole({IdentityInfoEnum.NORMAL_USER, IdentityInfoEnum.HOSPITAL_ADMIN, IdentityInfoEnum.SUPER_ADMIN})
    public Boolean changePassword(@Valid @RequestBody ChangePasswordRequest request, HttpServletRequest httpRequest) {
        Integer userId = (Integer) httpRequest.getAttribute("userId");
        return userService.changePassword(userId, request);
    }
}
